﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Text;
using System.Threading.Tasks;

namespace ABELGX
{
    /// <summary>
    /// 电池
    /// </summary>
    public class InfoBattery:CarInfo
    {
        public BatterySet Set { get; }
        /// <summary>
        /// 电压
        /// </summary>
        public Sensor Voltage { get; set; }
        /// <summary>
        /// 电流
        /// </summary>
        public Sensor Current { get; set; }
        /// <summary>
        /// 电量
        /// </summary>
        public Sensor Quantity { get; set; }
        public List<BatteryCell> Cells { get; set; } = new List<BatteryCell>();

        public InfoBattery(BatterySet set, params byte[] func) : base(func)
        {
            Set = set;
            Voltage = new Sensor(set.Voltage);
            Current = new Sensor(set.Current);
            Quantity = new Sensor(set.Quantity);
            while (Cells.Count < set.Count)
            {
                Cells.Add(new BatteryCell(set.CellVoltage, set.CellTemperature, Cells.Count + 1));
            }
        }

        public override void ProcessData(byte[] data, int start)
        {
            int i = start + 1;
            switch (data[start])
            {
                case INFO_BATTERY:
                    Voltage.Value = BitConverter.ToUInt16(data, i) * Set.Voltage.Scale;
                    i += 2;
                    Current.Value = BitConverter.ToInt16(data, i) * Set.Current.Scale;
                    i += 2;
                    Quantity.Value = BitConverter.ToUInt16(data, i) *Set.Quantity.Scale;
                    break;
                case INFO_BATTERY_VOLTAGE:
                    for (int j = 0; j < Cells.Count; i += 2, j++)
                    {
                        Cells[j].Voltage.Value = BitConverter.ToUInt16(data, i) * Set.CellVoltage.Scale;
                    }
                    break;
                case INFO_BATTERY_TEMPERATURE:
                    for (int j = 0; j < Cells.Count; i += 2, j++)
                    {
                        Cells[j].Temperature.Value = BitConverter.ToUInt16(data, i) * Set.CellTemperature.Scale;
                    }
                    break;
                default:
                    break;
            }
        }

        public override void InitData()
        {
            Voltage.Value = 0;
            Current.Value = 0;
            Quantity.Value = 0;
            foreach (var cell in Cells)
            {
                cell.Voltage.Value = 0;
                cell.Temperature.Value = 0;
            }
        }
    }
}
